"""
pagamiago - free software script to send PayPal payments

Copyright (C) 2018 Alyssa Rosenzweig

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
"""

import pagamigo.validator as Validator
from pagamigo.helpers import grep_json_string
from pagamigo.helpers import ProgressBar

ID = "send-money"
DESCRIPTION = "Send money to a friend via PayPal"

ARGS = {
    "recipient_email": (
        "Recipient's email address",
        "address",
        Validator.email),
    "amount": (
        "Amount to be transferred (1.21 for $1.21)",
        "amount",
        Validator.amount)}


def flow(session, recipient_email, amount, debug=False):
    session.referer = "/myaccount/transfer/send/preview"
    progress_bar = ProgressBar("Money Transfer", 4)

    send = session.send_request("/myaccount/transfer/send",
                                {}, plain_headers=True, )
    progress_bar.update(debug)

    session.referer = "/myaccount/transfer/send"
    session.headers["X-CSRF-Token"] = grep_json_string(send, "token")

    progress_bar.update(debug)

    fi = session.send_request("/myaccount/transfer/fi", {
        "env": "",
        "recipient": recipient_email,
        "amount": amount,
        "currencyCode": "USD",
        "goods": "false",
        "action": "send",
        "themeId": "",
        "flowType": "send",
        "paymentCardId": "",
        "conversionType": "",
        "recipientCountry": ""
    }, mode="post_form")
    progress_bar.update(debug)

    session.send_request("/myaccount/transfer/send", {
        "env": "",
        "action": "send",
        "whoPaysFee": "sellerPaysFee",
        "recipient": recipient_email,
        "fundingOptionId": fi["data"]["fundingOptions"][0]["id"],
        "description": "",
        "donationGiftAidCheckbox": "false",
        "flowType": "send"
    }, mode="post_form")
    progress_bar.update(debug)

    return True
